// ignore_for_file: unnecessary_null_comparison, non_constant_identifier_names

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:verse_systems/commom/models/chat_info_model.dart';
import 'package:verse_systems/commom/routers/fade_route.dart';
import 'package:verse_systems/pages/service/service_control.dart';
import 'package:verse_systems/res/colors.dart';
import 'package:verse_systems/utils/image_utils.dart';
import 'package:verse_systems/widgets/photoview_simplescreen.dart';

class ServicePage extends StatefulWidget {
  const ServicePage({super.key});

  @override
  State<ServicePage> createState() => _ServicePageState();
}

class _ServicePageState extends State<ServicePage> {
  final control = Get.put(MessageControl());
  final state = Get.find<MessageControl>().state;

  //创建
  FocusNode focusNode = FocusNode();

  // late  double keyboardHeight = 0;

  @override
  void initState() {
    super.initState();
    //2.添加监听
    focusNode.addListener(() {
      if (focusNode.hasFocus) {
        debugPrint("获得焦点");
        control.onTapHide();
      } else {
        debugPrint("失去焦点");
      }
    });
  }

  @override
  void dispose() {
    focusNode.removeListener(() => {});
    super.dispose();
  }

  Widget get _listView {
    return Expanded(
      child: ListView.builder(
        controller: control.scrollController,
        itemCount: state.chatList.length,
        itemBuilder: (BuildContext context, int index) {
          ChatInfoModel model = state.chatList[index];
          return Padding(
              padding: EdgeInsets.fromLTRB(13.w, 8.w, 14.w, 8.w),
              child: _customerWidget(model: model));
        },
      ),
    );
  }

  Widget _chatImageWidget({required ChatInfoModel model}) {
    if (model.messageType == 0) {
      return Row(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            _chatWidget(model: model),
            SizedBox(width: 5.w),
            Row(children: [
              Text(model.messageTime.toString(),
                  style: TextStyle(
                      color: Colours.app_main_color,
                      fontSize: 11.sp,
                      letterSpacing: -0.29)),
              (model.sendSuccess == true && model.readSuccess == true)
                  ? Image.asset(
                      ImageUtils.getImgPath("checks"),
                      fit: BoxFit.fill,
                      width: 17.w,
                      height: 8.w,
                    )
                  : const Icon(
                      Icons.check,
                      color: Colours.app_main_color,
                      size: 17,
                    )
            ])
          ]);
    }
    return Stack(
      children: [
        _chatWidget(model: model),
        Positioned(
            bottom: 5,
            right: 5,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 5.w, vertical: 2.w),
              decoration: BoxDecoration(
                color: Colours.stringAnAlphaColor("0xff000000", alpha: 0.2),
                borderRadius: BorderRadius.all(Radius.circular(7.w)),
              ),
              child: Row(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text(model.messageTime.toString(),
                        style: TextStyle(
                            color: Colours.app_main_color,
                            fontSize: 11.sp,
                            letterSpacing: -0.29)),
                    (model.sendSuccess == true && model.readSuccess == true)
                        ? Image.asset(
                            ImageUtils.getImgPath("checks"),
                            fit: BoxFit.fill,
                            width: 17.w,
                            height: 8.w,
                          )
                        : const Icon(
                            Icons.check,
                            color: Colours.app_main_color,
                            size: 17,
                          ),
                  ]),
            ))
      ],
    );
  }

  Widget _customerWidget({required ChatInfoModel model}) {
    if (model.send == true) {
      return Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          ClipPath(
              clipper: BubbleViewClip(BubbleViewClipDirection.right),
              child: Container(
                color: model.messageType == 0
                    ? Colours.app_chat_text_background_color
                    : Colors.transparent,
                padding: EdgeInsets.only(
                    left: 10.w,
                    right: BubbleViewClip.ARRWIDTH + 5.w,
                    top: 5.w,
                    bottom: 5.w),
                child: _chatImageWidget(model: model),
              )),
        ],
      );
    }
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        ClipPath(
          clipper: BubbleViewClip(BubbleViewClipDirection.left),
          child: Container(
            color: model.messageType == 0
                ? Colours.app_main_color
                : Colors.transparent,
            padding:
                EdgeInsets.only(left: 20.w, right: 10.w, top: 5.w, bottom: 5.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(model.name.toString(),
                    style: TextStyle(
                        color: const Color(0xFF02C1A6),
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w500)),
                Row(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    _chatWidget(model: model),
                    SizedBox(width: 5.w),
                    Text(model.messageTime.toString(),
                        style: TextStyle(
                            color: Colours.calendar_open_text_color,
                            fontSize: 11.sp,
                            letterSpacing: -0.29))
                  ],
                )
              ],
            ),
          ),
        )
      ],
    );
  }

  Widget _chatWidget({required ChatInfoModel model}) {
    if (model.messageType == 0) {
      return Container(
        constraints: BoxConstraints(
          maxWidth: MediaQuery.of(context).size.width - 200.w, // 最大宽度
        ),
        child: Text(model.message.toString(),
            softWrap: true,
            style: TextStyle(
                color: model.send == true
                    ? Colours.app_main_color
                    : const Color(0xFF2C2C2C),
                fontSize: 16.sp,
                fontWeight: FontWeight.w400,
                letterSpacing: -0.39)),
      );
    }
    return InkWell(
        onTap: () {
          debugPrint("点击图片");
                 Navigator.of(context).push(FadeRoute(
                page: PhotoViewSimpleScreen(
              imageProvider: NetworkImage(model.message.toString()),
            )));
        },
        child: ClipRRect(
            borderRadius: BorderRadius.circular(8.w),
            child: CachedNetworkImage(
              fit: BoxFit.fill,
              width: 152.w,
              height: 156.w,
              imageUrl: model.message.toString(),
              placeholder: (context, url) => Transform.scale(
                scale: 0.5,
                child: const CircularProgressIndicator(
                  color: Colours.app_main_background_color,
                ),
              ),
              errorWidget: (context, url, error) =>
                  const Icon(Icons.error_outline_outlined),
            )));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colours.system_background_color,
        appBar: AppBar(
          backgroundColor: Colours.app_main_color,
          title: Text(
            'my_service'.tr,
            style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.normal,
                color: Colours.drawer_text_color),
          ),
          elevation: 0,
          centerTitle: true,
        ),
        body: GetBuilder<MessageControl>(
            init: control,
            builder: (_) {
              return GestureDetector(
                  onTap: () {
                    FocusScope.of(context).unfocus();
                  },
                  child: Column(
                    children: <Widget>[
                      _listView,
                      Container(
                        color: const Color(0xFFD8D8D8),
                        padding: EdgeInsets.symmetric(
                            vertical: 10.w, horizontal: 10.w),
                        child: Row(
                          children: <Widget>[
                            Expanded(
                                child: Container(
                              constraints: BoxConstraints(
                                  minHeight: 30.w, maxHeight: 100.w),
                              padding: EdgeInsets.symmetric(horizontal: 5.w),
                              decoration: BoxDecoration(
                                color: Colours.app_main_color,
                                borderRadius:
                                    BorderRadius.all(Radius.circular(5.w)),
                              ),
                              child: TextField(
                                focusNode: focusNode,
                                maxLines: null,
                                textInputAction: TextInputAction.send,
                                keyboardType: TextInputType.text,
                                textAlign: TextAlign.left, //文本对齐方式
                                style: TextStyle(
                                  fontSize: 15.sp,
                                  color: Colours.app_black_text_color,
                                ),
                                decoration: InputDecoration(
                                    contentPadding:
                                        EdgeInsets.symmetric(vertical: 5.w),
                                    border: InputBorder.none,
                                    hintText: "message",
                                    counterText: '',
                                    hintStyle: TextStyle(
                                      fontSize: 15.sp,
                                    )),
                                showCursor: true,
                                cursorColor: Colours.app_main_background_color,
                                onChanged: (v) {
                                  // state.mobileForCode = v;
                                },
                                onEditingComplete: control.handleSend,
                                controller: control.messageController,
                              ),
                            )),
                            SizedBox(width: 10.w),
                            InkWell(
                              onTap: () {
                                control.onTapShow();
                                FocusScope.of(context).unfocus();
                              },
                              child: Image.asset(
                                ImageUtils.getImgPath("add_icon"),
                                fit: BoxFit.fill,
                                width: 28.w,
                                height: 28.w,
                              ),
                            )
                          ],
                        ),
                      ),
                      ChatBottom(
                        chatBottom: state.chatBottom,
                        onChatTap: control.onChatTap,
                        onUploadTap: control.onUploadTap,
                      )
                    ],
                  ));
            }));
  }
}

typedef OnChatTap = void Function(Map result);
typedef OnUploadTap = void Function();

class ChatBottom extends StatelessWidget {
  final bool chatBottom;
  final OnChatTap onChatTap;
  final OnUploadTap onUploadTap;
  const ChatBottom(
      {super.key,
      required this.chatBottom,
      required this.onChatTap,
      required this.onUploadTap});

  @override
  Widget build(BuildContext context) {
    return chatBottom
        ? Container(
            height: 150.w,
            color: Colours.system_background_color,
            child: Column(
              children: [
                Row(
                  children: _idCard,
                ),
                RichText(
                    text: TextSpan(children: [
                  TextSpan(
                    text: 'upload_error'.tr,
                    style: TextStyle(
                      color: Colours.app_black_text_color,
                      fontSize: 12.sp,
                    ),
                  ),
                  TextSpan(
                    text: 'click_here'.tr,
                    style: TextStyle(
                      color: Colours.blue_text_color,
                      fontSize: 12.sp,
                      // decoration: TextDecoration.underline,
                    ),
                    recognizer: TapGestureRecognizer()..onTap = onUploadTap,
                  ),
                  TextSpan(
                    text: 'upload'.tr,
                    style: TextStyle(
                      color: Colours.app_black_text_color,
                      fontSize: 12.sp,
                    ),
                  ),
                ]))
              ],
            ),
          )
        : Container();
  }

  List<Widget> get _idCard {
    return [
      {
        "title": "photo".tr,
        "image": "chat",
        "index": 0,
        "path": ImageUtils.getImgPath("photo_icon"),
      },
      {
        "title": "take_picture".tr,
        "image": "chat",
        "index": 1,
        "path": ImageUtils.getImgPath("camera_icon"),
      },
    ].map((val) {
      return InkWell(
          onTap: () {
            onChatTap(val);
          },
          child: Container(
              padding: EdgeInsets.symmetric(vertical: 17.w, horizontal: 21.w),
              child: Column(
                children: [
                  Image.asset(
                    val["path"].toString(),
                    fit: BoxFit.fill,
                    width: 63.w,
                    height: 62.w,
                  ),
                  SizedBox(height: 9.w),
                  Text(
                    val["title"].toString(),
                    style: TextStyle(
                        fontSize: 12.sp,
                        fontWeight: FontWeight.normal,
                        color: Colours.drawer_text_color),
                  ),
                ],
              )));
    }).toList();
  }
}

enum BubbleViewClipDirection { top, bottom, right, left, topLeft }

class BubbleViewClip extends CustomClipper<Path> {
  /// 夹角宽度
  static double ARRWIDTH = 10;

  /// 夹角高度
  double arrHeight = 10;

  /// 气泡框圆角 /// 夹角圆角自己写去吧
  double radius = 5;

  /// 夹角Y位置
  double arrPointY = 15;

  BubbleViewClipDirection direction;

  BubbleViewClip(this.direction);
  @override
  Path getClip(Size size) {
    double height = size.height;
    double width = size.width;

    if (direction == BubbleViewClipDirection.right) {
      var controllPoint = Offset(width, arrPointY + arrHeight / 2);
      var endPoint =
          Offset(width - (ARRWIDTH / 2), arrPointY + arrHeight / 4 * 3);

      Path zone = Path()
        ..addRRect(RRect.fromLTRBR(
            0, 0, width - ARRWIDTH, height, Radius.circular(radius)))
        // ..close()
        ..moveTo(width - ARRWIDTH, arrPointY)
        ..lineTo(width - (ARRWIDTH / 2), arrPointY + arrHeight / 4)
        ..quadraticBezierTo(
            controllPoint.dx, controllPoint.dy, endPoint.dx, endPoint.dy)
        ..lineTo(width - ARRWIDTH, arrPointY + arrHeight)
        ..lineTo(width - ARRWIDTH, arrPointY)
        ..close();

      return zone;
    } else {
      var controllPoint = Offset(0, arrPointY + arrHeight / 2);
      var endPoint = Offset(ARRWIDTH / 2, arrPointY + arrHeight / 4 * 3);

      Path zone = Path()
        ..addRRect(RRect.fromLTRBR(
            ARRWIDTH, 0, width, height, Radius.circular(radius)))
        // ..close()
        ..moveTo(ARRWIDTH, arrPointY)
        ..lineTo(ARRWIDTH / 2, arrPointY + arrHeight / 4)
        ..quadraticBezierTo(
            controllPoint.dx, controllPoint.dy, endPoint.dx, endPoint.dy)
        ..lineTo(ARRWIDTH, arrPointY + arrHeight)
        ..lineTo(ARRWIDTH, arrPointY)
        ..close();

      return zone;
    }
  }

  @override
  bool shouldReclip(covariant CustomClipper oldClipper) {
    return true;
  }
}
